import axios from 'axios'
import router from '@/router/index'
import store from '@/store/index'
import {BASIC_URL, AXIOS_TIME_OUT, AXIOS_WITH_CREDENTIALS} from '@/api/config'
import {getToken, clearToken} from '@/api/cache'
import {Loading, Message} from 'element-ui'
// import {Message} from 'element-ui'
axios.defaults.timeout = AXIOS_TIME_OUT
axios.defaults.withCredentials = AXIOS_WITH_CREDENTIALS
axios.defaults.baseURL = BASIC_URL
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'

export class _axios {
  constructor (basicUrl) {
    this.loadingInstace = null
    this.$axios = axios.create({
      baseURL: basicUrl,
      timeout: AXIOS_TIME_OUT,
      headers: {
        // 'X-Custom-Header': 'foobar',
        post: {
          'Content-Type': 'application/json; charset=utf-8'
        }
      },
      withCredentials: AXIOS_WITH_CREDENTIALS
    })
    // 请求拦截器
    this.$axios.interceptors.request.use(
      req => {
        this.loadingInstace = Loading.service({
          fullscreen: true,
          background: 'transparent'
        })
        let isLogin = store.dispatch('isLogin')
        req.headers.token = isLogin && getToken()
        return req
      },
      err => {
        this.loadingInstace.close()
        Message.error({
          message: '加载超时'
        })
        return Promise.reject(err)
        // return Promise.reject(err.data.error.message)
      }
    )
    // 响应拦截器
    this.$axios.interceptors.response.use(
      res => {
        this.loadingInstace.close()
        if (res.data.code === 401) {
          clearToken()
          Message.error('您的登录状态已失效，请重新登录！')
          router.replace({
            path: '/login'
          })
        } else {
          return res
        }
        return res
      },
      err => {
        // 拦截401错误
        this.loadingInstace.close()
        if (err.response) {
          switch (err.response.status) {
            case 401:
              console.log('响应拦截器....')
              // 这里写清除token的代码
              clearToken()
              router.replace({
                path: 'login'
              })
              break
            default:
              // Message.error({
              //   message: '加载失败'
              // })
              break
          }
        }
        return Promise.reject(err)
      }
    )
    // return this.$axios
  }
  // 封装axios 的 get 方法
  get (url, param = {}, data = {}) {
    return new Promise((resolve, reject) => {
      this.$axios({
        url,
        method: 'get',
        params: param,
        data: data
      }).then(
        res => {
          resolve(res.data)
        },
        err => {
          reject(err)
        }
      )
    })
  }
  // 封装axios 的 post 方法
  post (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
      this.$axios({
        url,
        method: 'post',
        data: data
      }).then(
        res => {
          resolve(res.data)
        },
        err => {
          reject(err)
        }
      )
    })
  }
  axios$ (param) {
    return new Promise((resolve, reject) => {
      this.$axios(param).then(
        res => {
          resolve(res)
        },
        err => {
          reject(err)
        }
      )
    })
  }
  axiosAll (arr = []) {
    return Promise.all(arr).then(
      (res) => {
        return new Promise((resolve, reject) => {
          if (res.length) {
            resolve(res)
          } else {
            reject(res)
          }
        })
      },
      err => {
        Promise.reject(err)
      }
    )
  }
}

export const $http = new _axios(BASIC_URL)
export const $httpMock = new _axios('/rent')
